<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>推流页面</title>
</head>

<body>
  <div>

  </div>
  <script>
    // datachannel对象
    let datachannel = null;

    // 推流用的MediaStream
    let pc_pub = null;

    let ws = new WebSocket('ws://127.0.0.1:9000');
    ws.addEventListener('open', () => {
      // 通知server pub已经上线
      ws.send(JSON.stringify({
        type: "publish"
      }))
    })

    ws.addEventListener('message', (event) => {
      let msg = JSON.parse(event.data);
      switch (msg.type) {
        case "start":
          start();
          break;

        case "answer":
          pc_pub.setRemoteDescription(msg).then(() => {

          }).catch((err) => {

          })
          break;

        default:
          pc_pub.addIceCandidate(msg);
          break;
      }
    })



    function start() {
      pc_pub = new RTCPeerConnection();
      pc_pub.addEventListener('icecandidate', (event) => {
        if (event.candidate) {
          ws.send(JSON.stringify(event.candidate));
        }
      })
      addDataChannel();
      pc_pub.createOffer().then((offer) => {
        pc_pub.setLocalDescription(offer).then(() => {
          ws.send(JSON.stringify(offer));
        }).catch((err) => {
          console.error('setLocalDescription error', err);
        })
      }).catch((err) => {
        console.error("create offer error", err);
      })
    }


    function addDataChannel() {
      datachannel = pc_pub.createDataChannel('dc', {
        ordered: true,
        id: 1,
      });
      datachannel.addEventListener('open', onDataChannelOpen);
      datachannel.addEventListener('close', onDataChannelClose);
      datachannel.addEventListener('error', onDataChannelError);
      datachannel.addEventListener('message', onDataChannelMessage);
    }


    function onDataChannelOpen() {
      console.log("pub datachannel open")
    }

    function onDataChannelClose() {
      console.log("pub datachannel close")
    }

    function onDataChannelError() {
      console.log("pub datachannel error")
    }

    function onDataChannelMessage(event) {
      console.log("pub datachannel messae:", event.data)
    }



  </script>
</body>

</html>